// pages/batchbind/batchbind.ts
import api from "../../utils/api";
import readExcel from "../../utils/selectAndParseExcel"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    excelResult: [] as BindSampleParam[],// excel识别结果
  },
  // 上传文件
  async uploadFile(): Promise<void> {
    try {
      const result = await readExcel();
      let excelResult = this.data.excelResult;
      for (let item of result) {
        excelResult.push(item);
      }
      this.setData({
        excelResult: excelResult
      })
    } catch (error) {
      wx.showToast({
        title: error,
        icon: "error"
      })
    }
  },
  // 确认绑定
  batchBind(): void {
    api.sampleBind.batchBind(this.data.excelResult).then(res => {
      console.log(res)
      if (res.data.code == "000") {
        //@ts-ignore
        let results: Array<BatchBandResult> = res.data.data;

        let successCount = 0;
        let failCount = 0;
        let failList = [];
        for (const result of results) {
          //@ts-ignore
          let index: number = result.index;
          if (result.success) {
            successCount += 1;
          } else {
            failCount += 1;
            let item = this.data.excelResult[index];
            //@ts-ignore
            item.failMessage = result.message;
            failList.push(item);
          }
        }
        if (failCount > 0) {
          wx.showModal({
            title: '上传完成',
            content: '成功' + successCount + '条，失败' + failCount + '条。',
            showCancel: false,
            confirmText: '查看原因'
          }).then(() => {
            this.setData({
              //@ts-ignore
              excelResult: failList
            })
          })
        } else {
          wx.showModal({
            title: '上传成功',
            content: '请选择接下来的操作',
            confirmText: '继续上传',
            cancelText: '返回首页'
          }).then(action => {
            if (action.confirm) {
              this.setData({
                excelResult: []
              })
            } else {
              wx.switchTab({
                url: '/pages/index/index'
              })
            }
          })
        }
      } else {
        wx.showToast({
          title: res.data.message as string,
          icon: "error"
        })
      }
    })
  },
  // 手动添加
  handleAdd(): void {
    wx.navigateTo({
      url: "/pages/samplebinding/samplebinding?type=add"
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})